package com.study.tomcat.bio;

import com.study.tomcat.bio.http.MyBioRequest;
import com.study.tomcat.bio.http.MyBioResponse;
import com.study.tomcat.bio.http.MyBioServlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: huang
 * @Description 启动方法
 * @Date: 2021-01-16 13:07
 */
public class MyTomcatBio {

    private final Properties properties = new Properties();

    private final Map<String, MyBioServlet> servletMap = new HashMap<>();

    public static void main(String[] args) {
        new MyTomcatBio().start();
    }

    private void start() {
        init();

        try {
            int port = 8080;
            ServerSocket server = new ServerSocket(port);
            System.out.println("MY Tomcat 启动成功，监听端口为" + port);
            while (true) {
                Socket client = server.accept();

                process(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket client) {
        try {
            InputStream is = client.getInputStream();
            OutputStream os = client.getOutputStream();

            MyBioRequest request = new MyBioRequest(is);
            MyBioResponse response = new MyBioResponse(os);

            String url = request.getUrl();
            if(servletMap.containsKey(url)){
                servletMap.get(url).service(request,response);
            }else {
                response.write("404 - Not Found!");
            }

            os.flush();
            os.close();

            is.close();
            client.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() {
        try {
            String webInfo = this.getClass().getResource("/").getPath();
            FileInputStream fileInputStream = new FileInputStream(webInfo + "web-bio.properties");

            properties.load(fileInputStream);

            for (Object k : properties.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String servletName = key.replaceAll("\\.url$", "");
                    String url = properties.getProperty(key);
                    String className = properties.getProperty(servletName + ".className");
                    MyBioServlet servlet = (MyBioServlet) Class.forName(className).newInstance();
                    servletMap.put(url, servlet);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
